package com.ai.sys;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.TargetDataLine;

import com.ai.sys.http.NetworkHandler;
import com.ai.tool.CallBack;

public class SystemCheck {
	// 开始
	public void run() {
		try {
			checkNet();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 自检完成
	public void checkOver() {
		new SystemRun().run();
	}

	// 检查网络
	public void checkNet() throws InterruptedException {
		System.out.print("[网络组件]正在初始化.");
		int i = 0;
		while (i++ < 10) {
			System.out.print(".");
			Thread.sleep(500);
		}

		NetworkHandler biz = new NetworkHandler();
		biz.setJob(NetworkHandler.NET_JOB_TYPE.TEST_NET);
		biz.handleJob(new CallBack() {
			public void handleOver(Object respObj) {
				try {
					System.out.println("OK");
					// 检查语音
					checkVoice();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

			public void handleError(Exception e) {
				System.out.print("无法访问网络");
			}

			public void showNotice(String notice) {
			}
		});
	}

	// 检查语音
	public void checkVoice() throws InterruptedException {
		System.out.print("[语音识别模块]正在初始化.");
		int i = 0;
		while (i++ < 10) {
			System.out.print(".");
			Thread.sleep(500);
		}
		if (checkMicrophone() != true) {
			System.out.println("没有麦克风设备");
		} else {
			System.out.println("OK");
			checkOver();
		}

	}

	public boolean checkMicrophone() {
		try {
			float sampleRate = 44100;
			int sampleSizeInBits = 8;
			int channels = 1; // mono
			boolean signed = true;
			boolean bigEndian = true;
			AudioFormat format = new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian);
			DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
			final TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info);
			line.open(format);
			line.start();
			line.stop();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

}
